package com.zxm.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxm.edu.dao.SchoolDao;
import com.zxm.edu.entity.School;
import com.zxm.edu.exception.BizException;
import com.zxm.edu.service.SchoolService;
import com.zxm.edu.util.PageUtils;
import com.zxm.edu.vo.ConditionVO;
import com.zxm.edu.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 院校服务
 *
 * @author silencezheng
 * @date 2022/07/28
 */
@Service
public class SchoolServiceImpl extends ServiceImpl<com.zxm.edu.dao.SchoolDao, School> implements SchoolService {
    @Autowired
    private SchoolDao schoolDao;

    @Override
    public PageResult<School> listSchools(ConditionVO condition) {
        // 查询总量
        Integer count = schoolDao.getCount(condition);
        if (count <= 0) {
            return new PageResult<>();
        }
        // 查询课程列表
        List<School> schoolList = schoolDao.listSchoolBackDTO(PageUtils.getLimitCurrent(), PageUtils.getSize(), condition);
        return new PageResult<>(schoolList, count);
    }

    @Override
    public PageResult<School> listSchoolBackDTO(ConditionVO condition) {
        // 查询院校数量
        Integer count = schoolDao.selectCount(new LambdaQueryWrapper<School>()
                .like(StringUtils.isNotBlank(condition.getKeywords()), School::getName, condition.getKeywords()));
        if (count == 0) {
            return new PageResult<>();
        }
        // 分页查询院校列表
        List<School> schoolList = schoolDao.listSchoolBackDTO(PageUtils.getLimitCurrent(), PageUtils.getSize(), condition);
        return new PageResult<>(schoolList, count);
    }

    @Override
    public List<School> listSchoolsBySearch(ConditionVO condition) {
        // 搜索院校
        List<School> schoolList = schoolDao.selectList(new LambdaQueryWrapper<School>()
                .like(StringUtils.isNotBlank(condition.getKeywords()), School::getName, condition.getKeywords())
                .orderByDesc(School::getId));
        return schoolList;
    }

    @Override
    public void deleteSchool(List<Integer> schoolIdList) {
        schoolDao.deleteBatchIds(schoolIdList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateSchool(School school) {
        // 查询院校名是否存在
        School existSchool = schoolDao.selectOne(new LambdaQueryWrapper<School>()
                .select(School::getId)
                .eq(School::getName, school.getName()));
        if (Objects.nonNull(existSchool) && !existSchool.getId().equals(school.getId())) {
            throw new BizException("院校名已存在");
        }
        this.saveOrUpdate(school);
    }

}
